﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CRM.Database.Model;

namespace CRM.Syncroniser
{
  public  class SapCustomersHierarchySyncroniser :ISyncronise
    {
      #region Implementation of ISyncronise

      /// <summary>
      /// Запуск синхронизации
      /// </summary>
      /// <returns>Результат запуска</returns>
      public bool Syncronise()
      {
          var entities = new CRM.Database.Model.CRMEntities();
          var col = new CustomersCollection();
          var leCol = new LegalEntitiesCollection();

          foreach(var item in entities.SapCustomersHierarchy )
          {
              if (item.custId != null)
              {
                  Customers cust = col.GetCustomerBySAPNumber((int) item.custId);
                  //if(cust==null)
                  //{
                      
                  //}
                  if(cust!=null)
                  {
                      if (item.LEID != null)
                      {
                          int idLE = cust.GetLegalEntityBySapNumber((int) item.LEID);
                          if(idLE==0)
                          {
                              LegalEntities le = cust.GetLegalEntityByName(item.LEName);
                              if(le==null)
                              {
                                  le = new LegalEntities();
                                  le.IdCustomer = cust.IdCustomer;
                                  le.Name = item.LEName;
                                  le.NumberInSAP = (int?) item.LEID;

                                  leCol.Add(le, "Max" + DateTime.Now.ToShortDateString());
                              }
                              else
                              {
                                  le.NumberInSAP = (int?)item.LEID;
                                  leCol.Update(le, "Max" + DateTime.Now.ToShortDateString());
                              }
                          }
                      }
                  }
              }
          }


          return true;
      }

      #endregion
    }
}
